package com.lvyp.server.config.security;

import io.jsonwebtoken.Jwt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;
import springfox.documentation.spi.service.contexts.SecurityContext;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * jwt登录授权拦截器
 * 判断前端的请求头是否有token
 */
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Value("${jwt.tokenHeader}")  //  =Authorization 前端请求的键
    private String tokenHeader;
    @Value("${jwt.tokenHead}")  // =Bearer  前端请求的值
    private String tokenHead;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        String header = request.getHeader(tokenHeader);  // 从请求中获取请求头信息，使用键Authorization是否获取到值
        // 判断值是否为空，判断拿到的值是否是以Bearer开头的
        if (null != header && header.startsWith(tokenHead)) { //
            // 只截取出tokenHead的内容,获取token
            String token = header.substring(tokenHead.length());
            // 根据token获取用户名
            String username = jwtTokenUtil.getUserNameFromToken(token);
            // 判断username不为空，security全局上下文获取用户信息为空
            if (null != username && null == SecurityContextHolder.getContext().getAuthentication()) {
                // 根据用户名获取用户信息
                UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                // 验证token是否有效
                if (jwtTokenUtil.validateToken(token, userDetails)) {
                    UsernamePasswordAuthenticationToken authenticationToken =
                            new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
                    authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));  // 重新设置到用户对象
                    // 将用户对象放到security全局上下文
                    SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                }
            }
        }
        filterChain.doFilter(request,response);
    }
}
